package com.lee.mysql.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lee.mysql.dao.RoleDao;
import com.lee.mysql.dao.UserDao;
import com.lee.mysql.dao.UserRoleDao;
import com.lee.mysql.pojo.Role;
import com.lee.mysql.pojo.User;
import com.lee.mysql.pojo.UserRole;
import com.lee.mysql.util.DecryptUtil;
import com.lee.mysql.util.IdGenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 用户表
 */
@Slf4j
@Service
@Transactional
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;



    /** 新增用户表 */
    public int addRecord(User user){
        user.setId(IdGenUtil.flakeId());
        user.setIsAdmin(0);
        if (user.getLocked() == null){
            user.setLocked(0);
        }

        String deCodeB64 = DecryptUtil.deCodeB64(user.getPassword().trim());

        String salt = UUID.randomUUID().toString();
        String pwd = DecryptUtil.enCodeMD5(deCodeB64, salt);
        user.setPassword(pwd);
        user.setSalt(salt);

        int i = userDao.insertOne(user);

        if (i > 0 && StringUtils.isNotBlank(user.getRoleIds())){
            String[] ids = user.getRoleIds().split(",");
            List<UserRole> list = new ArrayList<>();
            Arrays.asList(ids).forEach(roleId->{
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(user.getId());
                list.add(userRole);
            });
            userRoleDao.batchInsert(list);
        }
        return i;
    }

    /** 根据ID修改记录 */
    public int updateOneById(User user){
        if (StringUtils.isNotBlank(user.getPassword())){
            String deCodeB64 = DecryptUtil.deCodeB64(user.getPassword().trim());
            String salt = UUID.randomUUID().toString();
            String pwd = DecryptUtil.enCodeMD5(deCodeB64, salt);
            user.setPassword(pwd);
            user.setSalt(salt);
        }else {
            user.setPassword(null);
            user.setSalt(null);
        }

        int i = userDao.updateById(user);
        if (i > 0 && StringUtils.isNotBlank(user.getRoleIds())){
            List<String> userIds = new ArrayList<>();
            userIds.add(user.getId());
            userRoleDao.deleteByUserIds(userIds);

            String[] ids = user.getRoleIds().split(",");
            List<UserRole> list = new ArrayList<>();
            Arrays.asList(ids).forEach(roleId->{
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(user.getId());
                list.add(userRole);
            });
            userRoleDao.batchInsert(list);
        }
        return i;
    }

    /** 修改密码 */
    public int updatePwdById(String userId,String oldPwd,String newPwd){
        User user = userDao.queryOneById(userId);

        oldPwd= DecryptUtil.deCodeB64(oldPwd.trim());
        String oldSalt = user.getSalt();
        String oldMd5 = user.getPassword();

        String checkMd5 = DecryptUtil.enCodeMD5(oldPwd, oldSalt);
        if (!oldMd5.equals(checkMd5)){
            return 999;
        }

        newPwd= DecryptUtil.deCodeB64(newPwd.trim());
        String newSalt = UUID.randomUUID().toString();
        String newMd5 = DecryptUtil.enCodeMD5(newPwd, newSalt);
        user.setPassword(newMd5);
        user.setSalt(newSalt);

        int i = userDao.updateById(user);
        return i;
    }

    /** 检测是否有超管 */
    public int checkIsAdmin(List<String> idList){
        return userDao.checkIsAdmin(idList);
    }

    /** 根据ID批量删除记录 */
    public int deleteByIds(List<String> idList){
        userRoleDao.deleteByUserIds(idList);
        return userDao.deleteByIds(idList);
    }

    /** 根据ID查询记录 */
    public User queryOneById(String id){
        User user = userDao.queryOneById(id);
        user.setPassword(null);
        user.setSalt(null);
        List<Role> roleList = roleDao.getUserRoleList(id);
        user.setRoleList(roleList);
        return user;
    }


    /** 查询分页数据 */
    public PageInfo<User> queryPaging(User record, Integer page, Integer size){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (loginUser.getIsAdmin() != User.ISADMIN){
            record.setIsAdmin(0);
        }

        PageHelper.startPage(page, size);
        List<User> list = userDao.getList(record);
        list.forEach(user -> {
            user.setPassword(null);
            user.setSalt(null);

            List<Role> roleList = roleDao.getUserRoleList(user.getId());
            user.setRoleList(roleList);
            StringBuilder nameStr = new StringBuilder();
            StringBuilder idStr = new StringBuilder();
            if (roleList.size() > 0){
                for (int i = 0; i < roleList.size(); i++) {
                    if (i == 0){
                        nameStr.append(roleList.get(i).getName());
                        idStr.append(roleList.get(i).getId());
                    }else {
                        nameStr.append(",").append(roleList.get(i).getName());
                        idStr.append(",").append(roleList.get(i).getId());
                    }
                }
            }
            user.setRoleNames(nameStr.toString());
            user.setRoleIds(idStr.toString());
        });

        return new PageInfo<>(list);
    }


    /** 导出数据列表 */
    public List<User> exportList(User record){

        List<User> list = userDao.getList(record);

        return list;
    }


}
